import {observable, action} from "mobx";
import {ListViewPage} from "weaver-mobile-page";
import {Toast} from "weaver-mobile";
import {_scanQRCode} from "../../util";
import * as API from "../../api/cptApi";


export default class InventoryDetailStore {
    @observable showCheck = false;
    @observable from = "";
    @observable inventoryId = "";
    @observable detailList;
    @observable searchValue = "";
    @observable searchValue2 = "";
    @observable chooseIndex = -1;
    @observable cptState = -1;


    @action
    whereFrom = (from) => {
        this.from = from;
        this.detailList = new ListViewPage.Store({route: "/inventoryDetail", id: from});
    };
    @action
    init = (id, newPage) => {
        this.inventoryId = id;
        if (newPage === "1") {
            this.cptState = -1;
        }
        this.chooseIndex = this.cptState;
        this.onSearch();
    };
    @action
    changeSearchValue = (val) => {
        if (this.from !== "inventoried") {
            this.searchValue = val;
        } else {
            this.searchValue2 = val;
        }
    };
    @action
    chooseState = (opt) => {
        if (this.chooseIndex === opt.index) {
            this.chooseIndex = -1;
            this.cptState = "";
        } else {
            this.chooseIndex = opt.index;
            this.cptState = this.chooseIndex;
        }
        this.onSearch();    //带参请求数据
    };

    @action
    onSearch = () => {
        const list = this.detailList;
        let params = {
            inventoryId: this.inventoryId,
            state: this.cptState,
            name: this.from !== "inventoried" ? this.searchValue : this.searchValue2
        };
        // 清除列表数据
        list.clearData();
        // 带参数请求列表数据
        this.getInventoryListDetail(list, params);
    };
    getInventoryListDetail = (list, params) => {
        API.getInventoryListDetail(params).then(res => {
            list.getData({dataKey: res.datas});
        })
    };

    @action
    scanInfo = (e, history) => {
        window.event ? window.event.cancelBubble = true : e.stopPropagation();
        _scanQRCode((data) => {
            const params = {
                mark: data,
                scantype: "inventory"
            };
            API.scanQRCodeCapital(params).then(res => {
                if (res.flag) {
                    history.push("/inventoryForm/" + this.inventoryId + "/" + res.capitalid + "/2");
                } else {
                    Toast.fail(res.msg, 2)
                }
            })
        })
    }
}
